<?php

declare(strict_types=1);

namespace App\Model;

use Hyperf\DbConnection\Model\Model;

/**
 *  App版本
 */
class AppVersion extends Model
{
    protected $table = 'app_version';

    const CACHE_KEY_LATEST = '';

    /**
     * 获取最新的版本信息
     * @param int $platform
     * @return mixed
     */
    static function getLatest(
        $platform = 1,
        $channel = '',
        $appId = 1,
        $role = 0,
        $gender = -1,
        $userType=1
    ) {
        $where = [
            ['app_id', $appId],
            ['flag', '=', 1],
            ['valid_at', '<=', date('Y-m-d H:i:s')]
        ];
        if($userType>0){
            $where[] = ['user_profile_id', '=',0];
        }
        $version = self::where($where)
            ->whereIn('platform', [0, $platform])
            ->whereIn('update_group', [$role, 0])
            ->whereIn('update_gender', [$gender, -1])
            ->where('channel', 'like', "%{$channel}%")
            ->orWhere(function ($query) use ($where, $platform, $role, $gender) {
                $query->where($where)
                    ->whereIn('platform', [0, $platform])
                    ->whereIn('update_group', [$role, 0])
                    ->whereIn('update_gender', [$gender, -1])
                    ->where('channel', '');
            })->orderBy('new_version', 'desc')->first();
        return $version ?: null;
    }

    /**
     * 当前ios在审核版本
     * @return string
     */
    static function iosChecking()
    {
        $version = self::getLatest();
        return $version ? $version->checking_version : '';
    }
}
